import { ref } from "vue";
import { timeSlot } from "@/utils";
import { getRegulatoryPerf } from "@/api/collaborativeInteractiveRresponse";
export function useChartAndTableHook(
  selValue,
  getMonthDataShowCalener,
  activeVppAndUser
) {
  const activeName = ref("first");

  // function getRandomNumberInRange(start, end) {
  //   const random = Math.random() * (end - start + 1) + start;
  //   return parseFloat(random.toFixed(2));
  // }

  let data = [];
  const times = timeSlot(15);
  const keys = Array(96)
    .fill(1)
    .map((_, index) => index + 1)
    .map(i => `p${i > 9 ? i : "0" + i}`);
  // times.forEach(item => {
  //   let c = [
  //     item,
  //     getRandomNumberInRange(4.9, 5), // 最大值
  //     getRandomNumberInRange(3.5, 4.8), // 实际值
  //     getRandomNumberInRange(3, 3.5), // 最小值
  //     getRandomNumberInRange(0, 6),
  //     getRandomNumberInRange(0, 6),
  //     getRandomNumberInRange(0, 6)
  //   ];
  //   data.push(c);
  // });

  const threeLineData = ref({
    baseLineUserLine: {},
    realDataUserLine: {},
    regulateUserLine: {}
  });
  const getThreeLineData = async () => {
    let res = await getRegulatoryPerf({
      date: selValue.value,
      vppId: activeVppAndUser.value[0],
      vppUserId: activeVppAndUser.value[1]
    });
    if (res) {
      threeLineData.value.baseLineUserLine = res.baseLineUserLine || {};
      threeLineData.value.realDataUserLine = res.realDataUserLine || {};
      threeLineData.value.regulateUserLine = res.regulateUserLine || {};
    } else {
      threeLineData.value = {
        baseLineUserLine: {},
        realDataUserLine: {},
        regulateUserLine: {}
      };
    }
    if (res.baseLineUserLine) {
      let data = [];
      keys.forEach(key => {
        data.push(res.baseLineUserLine[key] || null);
      });
      options.value.series[0].data = data;
    }
    if (res.realDataUserLine) {
      let data = [];
      keys.forEach(key => {
        data.push(res.realDataUserLine[key] || null);
      });
      options.value.series[2].data = data;
    }
    if (res.regulateUserLine) {
      let data = [];
      keys.forEach(key => {
        data.push(res.regulateUserLine[key] || null);
      });
      options.value.series[1].data = data;
    }
  };
  const options = ref({
    color: [
      "#fac858",
      "#91cc75",
      "#ee6666",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
      "#ea7ccc"
    ],
    grid: {},
    legend: {
      show: true,
      // data: ["响应能力", "日前计划", "实际", "APC"]
      data: ["基线", "计划", "实际"]
    },
    dataZoom: [
      {
        type: "inside",
        start: 0,
        end: 100
      },
      {
        show: true,
        type: "slider",
        top: "90%",
        start: 0,
        end: 100
      }
    ],
    tooltip: {
      trigger: "axis"
      // formatter(p) {
      //   if (
      //     p.length >= 2 &&
      //     p[0].seriesType === "candlestick" &&
      //     p[1].seriesType === "candlestick"
      //   ) {
      //     let markerOne = p[0].marker;
      //     let max = p[0].value[1];
      //     let min = p[0].value[3];
      //     let str = "";
      //     p.forEach((item, index) => {
      //       if (index > 1) {
      //         str += `
      //       ${item.marker}${item.seriesName}: ${item.value}<br/>
      //       `;
      //       }
      //     });
      //     return (
      //       `${markerOne}响应能力<br/>
      //       上限：${max}<br/>
      //     下限：${min}<br/>
      //     ` + str
      //     );
      //   } else {
      //     let str = "";
      //     p.forEach(item => {
      //       str += `
      //       ${item.marker}${item.seriesName}: ${item.value}<br/>
      //       `;
      //     });
      //     return str;
      //   }
      // }
      // axisPointer: {
      //   type: 'cross'
      // }
    },
    xAxis: {
      splitLine: {
        show: false
      },
      data: times
    },
    yAxis: [
      {
        name: "kW",
        nameLocation: "end",
        splitLine: {
          show: false
        },
        axisLine: {
          show: true
        }
      }
    ],
    series: [
      // {
      //   name: "响应能力",
      //   type: "candlestick",
      //   // 最大值  最大值 - 1 最小值 最小值+1
      //   data: data.map(item => {
      //     return [item[1], item[1] - 0.01, item[3], item[3] + 0.01];
      //   })
      // },
      // {
      //   name: "响应能力下限",
      //   type: "candlestick",
      //   // 最小值+1  最小值 - 1 最小值 - 1  最小值+1
      //   data: data.map(item => {
      //     return [
      //       item[3] + 0.01,
      //       item[3] - 0.01,
      //       item[3] - 0.01,
      //       item[3] + 0.01
      //     ];
      //   })
      // },
      {
        name: "基线",
        type: "line",
        smooth: true,
        data: []
      },
      {
        name: "计划",
        type: "line",
        smooth: true,
        data: []
      },
      {
        name: "实际",
        type: "line",
        smooth: true,
        data: []
      }
    ]
  });
  const options2 = ref({
    color: [
      "#fac858",
      "#91cc75",
      "#ee6666",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
      "#ea7ccc"
    ],
    grid: {},
    legend: {
      show: true,
      data: ["响应能力", "日前计划", "实际", "协同"]
    },
    dataZoom: [
      {
        type: "inside",
        start: 50,
        end: 100
      },
      {
        show: true,
        type: "slider",
        top: "90%",
        start: 50,
        end: 100
      }
    ],
    tooltip: {
      trigger: "axis",
      formatter(p) {
        if (
          p.length >= 2 &&
          p[0].seriesType === "candlestick" &&
          p[1].seriesType === "candlestick"
        ) {
          let markerOne = p[0].marker;
          let max = p[0].value[1];
          let min = p[0].value[3];
          let str = "";
          p.forEach((item, index) => {
            if (index > 1) {
              str += `
            ${item.marker}${item.seriesName}: ${item.value}<br/>
            `;
            }
          });
          return (
            `${markerOne}响应能力<br/>
            上限：${max}<br/>
          下限：${min}<br/>
          ` + str
          );
        } else {
          let str = "";
          p.forEach(item => {
            str += `
            ${item.marker}${item.seriesName}: ${item.value}<br/>
            `;
          });
          return str;
        }
      }
      // axisPointer: {
      //   type: 'cross'
      // }
    },
    xAxis: {
      splitLine: {
        show: false
      },
      data: data.map(item => item[0])
    },
    yAxis: [
      {
        name: "kW",
        nameLocation: "end",
        splitLine: {
          show: false
        },
        axisLine: {
          show: true
        }
      }
    ],
    series: [
      {
        name: "响应能力",
        type: "candlestick",
        // 最大值  最大值 - 1 最小值 最小值+1
        data: data.map(item => {
          return [item[1], item[1] - 0.01, item[3], item[3] + 0.01];
        })
      },
      {
        name: "响应能力下限",
        type: "candlestick",
        // 最小值+1  最小值 - 1 最小值 - 1  最小值+1
        data: data.map(item => {
          return [
            item[3] + 0.01,
            item[3] - 0.01,
            item[3] - 0.01,
            item[3] + 0.01
          ];
        })
      },
      {
        name: "日前计划",
        type: "line",
        smooth: true,
        lineStyle: {
          opacity: 0.2
        },
        // 实际值
        data: data.map(item => {
          return item[4];
        })
      },
      {
        name: "实际",
        type: "line",
        smooth: true,
        lineStyle: {
          opacity: 0.2
        },
        // 实际值
        data: data.map(item => {
          return item[5];
        })
      },
      {
        name: "APC",
        type: "line",
        smooth: true,
        lineStyle: {
          opacity: 0.2
        },
        // 实际值
        data: data.map(item => {
          return item[6];
        })
      }
    ]
  });

  const whole = ref(false);
  const showWhole = async () => {
    whole.value = true;
    await getThreeLineData();
  };
  const ruleFormRef = ref(null);
  const ruleForm = ref({
    name: undefined,
    region: undefined,
    start: undefined,
    end: undefined,
    target: undefined
  });
  const rules = ref({
    name: [
      { required: true, message: "请输入描述", trigger: "blur" },
      { min: 3, max: 50, message: "长度在3-50个字符之间", trigger: "blur" }
    ],
    region: [
      {
        required: true,
        message: "请选择投退状态",
        trigger: "change"
      }
    ],
    start: [
      {
        required: true,
        message: "请选择执行开始时间",
        trigger: "change"
      }
    ],
    end: [
      {
        required: true,
        message: "请选择执行结束时间",
        trigger: "change"
      }
    ],
    target: [
      { required: true, message: "请输入目标功率", trigger: "blur" },
      {
        validator: (rule: any, value: any, callback: any) => {
          let reg = /^-?\d+(.\d{1})?$/;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("请输入正确的数字!"));
          }
        },
        trigger: "blur"
      }
    ]
  });
  const cancel = () => {
    ruleFormRef.value && ruleFormRef.value.resetFields();
    ruleFormRef.value && ruleFormRef.value.clearValidate();
    whole.value = false;
  };
  const submit = () => {
    ruleFormRef.value.validate(valid => {
      if (valid) {
        cancel();
      }
    });
  };
  const handleClose = () => {
    cancel();
  };

  return {
    activeName,
    options,
    options2,
    data,
    whole,
    showWhole,
    ruleFormRef,
    ruleForm,
    rules,
    cancel,
    submit,
    handleClose
  };
}
